var nowSelectTemplate
var nowSelectTemplateTheme
var nowSelectTemplateThemeName
var nowSelectTemplateThemeSource
function openTemplate() {
    chartSource = JSON.parse(nowSelectTemplateSource)    
    chartSourceDis = nowSelectTemplateSource
    for (var i=0;i<chartParam.length;i++) {
        chartSourceDis = chartSourceDis.replace(new RegExp("\\${"+chartParam[i].param_name+"}","g"), chartParam[i].param_default)
    }

    $('#sourceContent2').html(formatSource(chartSource))
    
    Ext.getCmp('chartPreview').remove(0)
    Ext.getCmp('chartPreview').add(
        {
            listeners:{
                render:function( obj, eOpts ){
                    chart1.dispose()
                    echarts.registerTheme(nowSelectTemplateThemeName, JSON.parse(nowSelectTemplateThemeSource))
                    chart1 = echarts.init(document.getElementById('chart1'), nowSelectTemplateThemeName)
                    chart1.setOption(JSON.parse(chartSourceDis))
                    templateWindow.close()    
                    Ext.getCmp("chartTree").getSelectionModel().select(0)


                    Ext.getCmp('chartTree').getStore().getNodeById('chartInstance').removeAll()
                    nowChartTheme = nowSelectTemplateTheme

                    var seriesLength = chartSource.series.length
                    for(var i=0;i<seriesLength;i++) {
                        createSerieBand(chartSource.series[i].type,false)
                    }    

                }
            },
            xtype:'container',
            html:'<div id="chart1" style="width: 900px;height:'+(document.documentElement.clientHeight-400)+'px;"></div>',
        }
    )    

    
    

    //echarts.registerTheme(nowSelectTemplateThemeName, JSON.parse(nowSelectTemplateThemeSource))
    //chart1 = echarts.init(document.getElementById('chart1'),nowSelectTemplateThemeName);
    //chart1.setOption(chartSource)    
    
}


function saveTemplate() {
    if (Ext.getCmp('templateName').getValue() == "") {
        alert("请输入模板名")
        return
    }
    

    if (Ext.getCmp("templateTabPanel").getActiveTab()==null){
        alert("请先建立模板分类")
        return
    }

    Ext.Ajax.request({
        url: "../charttemplate/save",
        params: {
            themeId:nowChartTheme,
            templateName: Ext.getCmp('templateName').getValue(),
            templateDesc: Ext.getCmp('templateDesc').getValue(),
            templateSource: JSON.stringify(chartSource, null, "\t"),
            templateSrc:chart1.getDataURL(
                {
                    pixelRatio: 1
                    //backgroundColor: '#fff'
                }
            ),
            parentTemplateId: Ext.getCmp("templateTabPanel").getActiveTab().id.substring(11),
            isDir: false
        },
        success: function(response, opts) {
            var res = Ext.JSON.decode(response.responseText)
            console.log(res)
            
            templateWindow.close()
            Ext.toast('模板保存成功！');
            Ext.getCmp("templateDataView"+Ext.getCmp("templateTabPanel").getActiveTab().id).getStore().load()
        }
    });
}

var templateWindow = Ext.create('Ext.window.Window', {
    title: '',
    //iconCls:'x-fa fa-database',
    height: 900,
    width: 1100,
    //layout: 'fit',
    modal:true,
    closeAction:'hide',
    layout: 'border',
    defaults: {
        collapsible: false,
        split: true,
        bodyPadding: 0
    }, 
    items:[
        {
            title: '',
            region: 'south',
            //height: 65,
            width:'100%',
            scrollable: true,
            id:'templateNamePanel',
            items:[
                {
                    xtype:'textfield',
                    id:'templateName',
                    //labelWidth:700,
                    labelAlign:'right',
                    width:250,
                    fieldLabel: '模板名称'
                },
                {
                    xtype:'textarea',
                    id:'templateDesc',
                    //labelWidth:700,
                    height:100,
                    labelAlign:'right',
                    width:950,
                    fieldLabel: '模板名称'
                }
            ]
        },
        /*{
            title: '',
            region: 'west',
            width: 300,
            scrollable: true,
            items:[]
        },*/
        {
            title: '',
            region: 'center',
            width: '100%',
            scrollable: true,
            tbar: [
                { 
                    xtype: 'button', 
                    text: '增加模板分类',
                    iconCls:'x-fa fa-plus',
                    id:'addTemplateDir',
                    handler:function() {

                        Ext.MessageBox.show({
                            title: '增加模板分类',
                            msg: '请输入模板分类的名称:',
                            closable:false,
                            width:300,
                            buttons: Ext.MessageBox.OK,
                            multiline: true,
                            scope: this,
                            fn: function(btn, text) {
                                if(text=="") {
                                    alert('模板分类名称不能为空')
                                    return
                                }
                                Ext.Ajax.request({
                                    url: "../charttemplate/save",
                                    params:{isDir:'true',templateName:text},
                                    success:function(response, opts) {
                                        var res = Ext.JSON.decode(response.responseText)
                                        console.log(res.chartFile)
                                        if (res.success) {
                                            Ext.getCmp("templateTabPanel").add(
                                                {
                                                    id:'templateTab'+res.chartTemplate.id,
                                                    title:text,
                                                    scrollable:true,
                                                    listeners:{
                                                        render:function(obj,eOpts) {
                                                            obj.add(
                                                                {
                                                                    xtype: 'dataview',
                                                                    //height:300,
                                                                    id:'templateDataView'+obj.id,
                                                                    scroll:true,
                                                                    listeners:{
                                                                        select:function(obj, record, index, eOpts ) {
                                                                            
                                                                            nowSelectTemplate = record.data.id
                                                                            nowSelectTemplateTheme = record.data.theme_id
                                                                            nowSelectTemplateSource = record.data.template_source
                                                                            nowSelectTemplateThemeName = record.data.theme_name
                                                                            nowSelectTemplateThemeSource = record.data.theme_source
                                                                            Ext.getCmp("templateName").setValue(record.data.template_name)
                                                                            Ext.getCmp("templateDesc").setValue(record.data.template_desc)
                                                                        }
                                                                    },
                                                                    itemSelector: 'div.dataview-multisort-item',
                                                                    tpl: [
                                                                        '<tpl for=".">',
                                                                            '<div title="{template_desc}" class="dataview-multisort-item">',
                                                                                '<img src="{template_src}" style="width:314px;height:224px"/>',
                                                                                '<h3>{template_name}</h3>',
                                                                            '</div>',
                                                                        '</tpl>'
                                                                    ],
                                                                    store: {
                                                                        autoLoad: true,
                                                                        //sortOnLoad: true,
                                                                        fields: ['template_name', 'template_src', 'template_source', 'template_desc'],
                                                                        proxy: {
                                                                            type: 'ajax',
                                                                            url : '../charttemplate/store',
                                                                            extraParams:{isDir:"false",parentTemplateId:obj.id.substring(11)},
                                                                            reader: {
                                                                                type: 'json',
                                                                                rootProperty: ''
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            )
                                                        } 
                                                    },
                                                    items:[]
                                                }
                                            )
                                            Ext.getCmp("templateTabPanel").setActiveTab(Ext.getCmp("templateTabPanel").items.items.length-1)    
                                        } else {
                                            alert(res.message)
                                        }
                                    }
                                })
                                
                            }
                        });
   
                    }
                },
                { 
                    xtype: 'button', 
                    text: '删除模板分类',
                    iconCls:'x-fa fa-minus',
                    handler:function() {
                        Ext.Ajax.request({
                            url: "../charttemplate/delete",
                            params:{id:Ext.getCmp("templateTabPanel").getActiveTab().id.substring(11)},
                            success:function(response, opts) {
                                var res = Ext.JSON.decode(response.responseText)
                                if (res.success) {
                                    Ext.getCmp("templateTabPanel").getActiveTab().close()
                                } 
                            }
                        })
                    } 
                },
                { 
                    xtype: 'button', 
                    text: '修改模板分类',
                    iconCls:'x-fa fa-pencil',
                    handler:function() {
                        console.log(111)
                        console.log(Ext.getCmp("templateTabPanel").getActiveTab().title)
                        Ext.MessageBox.show({
                            title: '修改模板分类',
                            msg: '请输入模板分类的名称:',
                            closable:false,
                            width:300,
                            value:Ext.getCmp("templateTabPanel").getActiveTab().title,
                            buttons: Ext.MessageBox.OK,
                            multiline: true,
                            scope: this,
                            fn: function(btn, text) {
                                if(text=="") {
                                    alert('模板分类名称不能为空')
                                    return
                                }
                                Ext.Ajax.request({
                                    url: "../charttemplate/save",
                                    params:{isDir:'true',templateName:text,id:Ext.getCmp("templateTabPanel").getActiveTab().id.substring(11)},
                                    success:function(response, opts) {
                                        var res = Ext.JSON.decode(response.responseText)
                                        if (res.success) {
                                            Ext.getCmp("templateTabPanel").getActiveTab().setTitle(text)
                                        } else {
                                            
                                        }
                                    }
                                })
                            }
                        });
                    } 
                },
                { 
                    xtype: 'button', 
                    text: '删除模板',
                    iconCls:'x-fa fa-minus',
                    handler:function() {
                        if (nowSelectTemplate!=null) {
                            Ext.Ajax.request({
                                url: "../charttemplate/delete",
                                params:{id:nowSelectTemplate},
                                success:function(response, opts) {
                                    Ext.toast('模板删除成功！');
                                    Ext.getCmp("templateDataView"+Ext.getCmp("templateTabPanel").getActiveTab().id).getStore().load()            
                                }
                            })
                        }
                    } 
                }
            ],
            items:[
                {
                    xtype:'tabpanel',
                    id:'templateTabPanel',
                    //height:782:760,
                    width:1075,
                    scrollable:true,
                    items:[
                        /*{
                            title: '全部'
                        }, 
                        {
                            title: 'Bar',
                            tabConfig: {
                                title: 'Custom Title',
                                tooltip: 'A button tooltip'
                            }
                        }*/
                    ]
                }
            ]
        }
    ],
    buttons: [
        {
            xtype: 'button',
            text: '取消',
            handler: function() {
                templateWindow.close()
            }
        },
        {
            xtype: 'button',
            text: '确定',
            handler: function() {
                if (templateWindow.getTitle()=="导入模板") {
                    openTemplate()
                } else {
                    saveTemplate()
                }
            }
        }
    ]
})


Ext.Ajax.request({
    url: "../charttemplate/store",
    params:{isDir:'true'},
    success:function(response, opts) {
        var res = Ext.JSON.decode(response.responseText)
        for(var i=0;i<res.length;i++) {
            Ext.getCmp("templateTabPanel").add(
                {
                    id:'templateTab'+res[i].id,
                    title:res[i].template_name,
                    scrollable:true,
                    listeners:{
                        render:function(obj,eOpts) {
                            obj.add(
                                {
                                    xtype: 'dataview',
                                    //height:300,
                                    id:'templateDataView'+obj.id,
                                    scroll:true,
                                    listeners:{
                                        select:function(obj, record, index, eOpts ) {
                                            console.log(record.data)
                                            nowSelectTemplate = record.data.id
                                            nowSelectTemplateTheme = record.data.theme_id
                                            nowSelectTemplateSource = record.data.template_source
                                            nowSelectTemplateThemeName = record.data.theme_name
                                            nowSelectTemplateThemeSource = record.data.theme_source
                                            Ext.getCmp("templateName").setValue(record.data.template_name)
                                            Ext.getCmp("templateDesc").setValue(record.data.template_desc)
                                        }
                                    },
                                    itemSelector: 'div.dataview-multisort-item',
                                    tpl: [
                                        '<tpl for=".">',
                                            '<div title="{template_desc}" class="dataview-multisort-item">',
                                                '<img src="{template_src}" style="width:214px;height:154px"/>',
                                                '<h3>{template_name}</h3>',
                                            '</div>',
                                        '</tpl>'
                                    ],
                                    store: {
                                        autoLoad: true,
                                        //sortOnLoad: true,
                                        fields: ['template_name', 'template_src', 'template_source', 'template_desc'],
                                        proxy: {
                                            type: 'ajax',
                                            url : '../charttemplate/store',
                                            extraParams:{isDir:"false",parentTemplateId:obj.id.substring(11)},
                                            reader: {
                                                type: 'json',
                                                rootProperty: ''
                                            }
                                        }
                                    }
                                }
                            )
                        } 
                    },
                    items:[]
                }
            )
            Ext.getCmp("templateTabPanel").setActiveTab(0)
        }
       
    }
})